package com.joven.shelltest.utils.encrypt;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;

/**
 * hmac加密
 * @Author wzj
 * @Date 2023-11-30 14:22
 **/
public class HmacUtils {

    public static void main(String[] args) {
        String data = "123456";
        String hmac = hmacSha256(data);
        System.out.println("HMAC-SHA256: " + hmac);
    }

    public static String hmacSha256(String data) {
        try {
            // 生成密钥
            SecretKey secretKey = generateSecretKey();
            // 创建HMAC-SHA256的Mac实例
            Mac mac = Mac.getInstance("HmacSHA256");
            // 初始化Mac实例，并设置密钥
            mac.init(secretKey);
            // 计算认证码
            byte[] hmac = mac.doFinal(data.getBytes());
            return bytesToHex(hmac);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static SecretKey generateSecretKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacSHA256");
        return keyGenerator.generateKey();
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
